package com.example.fruitdb.controller;

import com.example.fruitdb.entity.vo.MessageModel;
import com.example.fruitdb.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class UserServlet extends HttpServlet
{
    private UserService userService = new UserService();

    /**
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        request.setCharacterEncoding("utf-8");
        //1.接收客户端请求（用户名、密码）
        String uname = request.getParameter("uname");
        String upassword = request.getParameter("upassword");

        //2.调用service方法 返回消息模型
        MessageModel messageModel = userService.userLogin(uname, upassword);

        //3.
        if(messageModel.getCode() == 1)
        {
            //登陆成功
            request.getSession().setAttribute("user",messageModel.getObject());
            request.getSession().setAttribute("login",true);
            response.sendRedirect("index.jsp");
        }
        else
        {
            //登陆失败
            request.setAttribute("messageModel",messageModel);
            request.getRequestDispatcher("admin.jsp").forward(request,response);

        }
    }
}
